﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TookKit.Mvvm.Helpers;
using TookKit.Mvvm.Interfaces;

namespace TookKit.Mvvm
{
    public class ModuleManager : IModuleManager
    {
        public string ModuleCatalog { get; set; } = string.Empty;

        public ConcurrentDictionary<string, Type> ModuleMaps { get; } = new ConcurrentDictionary<string, Type>();

        public ConcurrentDictionary<string, object> Instances { get; } = new ConcurrentDictionary<string, object>();

        public IModuleManager AddModule<T>()
        {
            //Type moduleType = typeof(T);
            AddModule(typeof(T));

            //if (!ModuleMaps.ContainsKey(moduleType.FullName))
            //{
            //    ModuleMaps.TryAdd(moduleType.FullName, moduleType);
            //}

            return this;
        }

        public IModuleManager AddModule(Type moduleType)
        {
            if (!ModuleMaps.ContainsKey(moduleType.FullName))
            {
                ModuleMaps.TryAdd(moduleType.FullName, moduleType);
            }

            return this;

        }

        public IModuleManager InitializeModules()
        {
            var assemblies = FileHelper.GetAssemblies(ModuleCatalog);

            foreach (Assembly assembly in assemblies)
            {
                var list = assembly.GetTypes();

                foreach (Type type in list)
                {
                    var moduleType = typeof(IModule);
                    //找模块的条件？
                    if (type.GetInterfaces().Contains(moduleType))
                    {
                        this.AddModule(type);
                    }
                }
            }

            return this;

        }
    }
}
